const { Op } = require('sequelize');
const Task = require('../models/Task');
const UserTask = require('../models/UserTask');
const User = require('../models/User');

const getAvailableTasks = async (req, res) => {
  try {
    const tasks = await Task.findAll({
      where: {
        isActive: true
      },
      order: [['createdAt', 'DESC']]
    });

    // 确保 reward 字段是 JSON 对象
    const formattedTasks = tasks.map(task => {
      const taskData = task.toJSON();
      if (typeof taskData.reward === 'string') {
        try {
          taskData.reward = JSON.parse(taskData.reward);
        } catch (e) {
          console.error('Failed to parse reward JSON:', e);
          taskData.reward = { experience: 0 };
        }
      }
      return taskData;
    });

    res.json({
      status: 'success',
      data: { tasks: formattedTasks }
    });
  } catch (error) {
    res.status(400).json({
      status: 'error',
      message: error.message
    });
  }
};

const startTask = async (req, res) => {
  try {
    const { taskId } = req.params;
    const userId = req.user.id;

    const task = await Task.findByPk(taskId);
    if (!task || !task.isActive) {
      return res.status(404).json({
        status: 'error',
        message: 'Task not found or inactive'
      });
    }

    // Check if user already has an active task
    const existingTask = await UserTask.findOne({
      where: {
        userId,
        taskId,
        status: {
          [Op.in]: ['pending', 'in_progress']
        }
      }
    });

    if (existingTask) {
      return res.status(400).json({
        status: 'error',
        message: 'Task already in progress'
      });
    }

    const userTask = await UserTask.create({
      userId,
      taskId,
      status: 'in_progress'
    });

    res.status(201).json({
      status: 'success',
      data: { userTask }
    });
  } catch (error) {
    res.status(400).json({
      status: 'error',
      message: error.message
    });
  }
};

const updateTaskProgress = async (req, res) => {
  try {
    const { taskId } = req.params;
    const { progress } = req.body;
    const userId = req.user.id;

    const userTask = await UserTask.findOne({
      where: {
        userId,
        taskId,
        status: 'in_progress'
      }
    });

    if (!userTask) {
      return res.status(404).json({
        status: 'error',
        message: 'Task not found or not in progress'
      });
    }

    userTask.progress = progress;
    await userTask.save();

    res.json({
      status: 'success',
      data: { userTask }
    });
  } catch (error) {
    res.status(400).json({
      status: 'error',
      message: error.message
    });
  }
};

const completeTask = async (req, res) => {
  try {
    const { taskId } = req.params;
    const userId = req.user.id;

    // 查找任务
    const userTask = await UserTask.findOne({
      where: {
        userId,
        taskId,
        status: {
          [Op.in]: ['pending', 'in_progress']
        }
      },
      include: [{
        model: Task,
        as: 'task'
      }]
    });

    if (!userTask) {
      return res.status(404).json({
        status: 'error',
        message: '任务不存在或已完成'
      });
    }

    const user = await User.findByPk(userId);
    const task = userTask.task;

    // 更新用户经验
    const experienceReward = task.reward.experience || 0;
    user.experience += experienceReward;

    // 检查是否升级
    if (user.experience >= user.nextLevelExp) {
      user.level += 1;
      user.experience = user.experience - user.nextLevelExp;
      user.nextLevelExp = Math.floor(user.nextLevelExp * 1.5); // 下一级所需经验增加50%
    }

    await user.save();

    // 更新任务状态
    userTask.status = 'completed';
    userTask.completedAt = new Date();
    await userTask.save();

    res.json({
      status: 'success',
      data: {
        userTask,
        rewards: {
          experience: experienceReward
        }
      }
    });
  } catch (error) {
    console.error('Error completing task:', error);
    res.status(400).json({
      status: 'error',
      message: error.message || '完成任务失败'
    });
  }
};

const getUserTasks = async (req, res) => {
  try {
    const userId = req.user.id;
    const userTasks = await UserTask.findAll({
      where: {
        userId,
        status: {
          [Op.in]: ['pending', 'in_progress', 'completed']
        }
      },
      include: [{
        model: Task,
        as: 'task',
        where: {
          isActive: true
        },
        attributes: ['id', 'title', 'description', 'type', 'reward', 'difficulty']
      }],
      order: [['createdAt', 'DESC']]
    });

    // 格式化任务数据
    const formattedTasks = userTasks.map(userTask => {
      const taskData = {
        id: userTask.taskId,
        userTaskId: userTask.id,
        title: userTask.task.title,
        description: userTask.task.description,
        type: userTask.task.type,
        difficulty: userTask.task.difficulty,
        status: userTask.status,
        progress: userTask.progress,
        reward: userTask.task.reward,
        createdAt: userTask.createdAt,
        completedAt: userTask.completedAt
      };

      // 确保 reward 是 JSON 对象
      if (typeof taskData.reward === 'string') {
        try {
          taskData.reward = JSON.parse(taskData.reward);
        } catch (e) {
          console.error('Failed to parse reward JSON:', e);
          taskData.reward = { experience: 0 };
        }
      }

      return taskData;
    });

    res.json({
      status: 'success',
      data: { userTasks: formattedTasks }
    });
  } catch (error) {
    console.error('Error fetching user tasks:', error);
    res.status(500).json({
      status: 'error',
      message: '获取用户任务失败'
    });
  }
};

const getAllTasks = async (req, res) => {
  try {
    const tasks = await Task.findAll({
      order: [['createdAt', 'DESC']]
    });

    const formattedTasks = tasks.map(task => {
      const taskData = task.toJSON();
      if (typeof taskData.reward === 'string') {
        try {
          taskData.reward = JSON.parse(taskData.reward);
        } catch (e) {
          taskData.reward = { experience: 0 };
        }
      }
      return taskData;
    });

    res.json({
      status: 'success',
      data: { tasks: formattedTasks }
    });
  } catch (error) {
    console.error('Error getting tasks:', error);
    res.status(500).json({
      status: 'error',
      message: error.message
    });
  }
};

const getLatestTasks = async (req, res) => {
  try {
    const tasks = await Task.findAll({
      attributes: ['id', 'title', 'description', 'type', 'difficulty', 'reward', 'isActive', 'createdAt'],
      where: {
        isActive: true
      },
      order: [['createdAt', 'DESC']],
      limit: 5 // 只返回最新的5个任务
    });

    // 确保 reward 字段是 JSON 对象
    const formattedTasks = tasks.map(task => {
      const taskData = task.toJSON();
      if (typeof taskData.reward === 'string') {
        try {
          taskData.reward = JSON.parse(taskData.reward);
        } catch (e) {
          console.error('Failed to parse reward JSON:', e);
          taskData.reward = { experience: 0 };
        }
      }
      return taskData;
    });

    res.json({
      status: 'success',
      data: { tasks: formattedTasks }
    });
  } catch (error) {
    console.error('Error getting latest tasks:', error);
    res.status(500).json({
      status: 'error',
      message: error.message
    });
  }
};

module.exports = {
  getAllTasks,
  getAvailableTasks,
  getUserTasks,
  startTask,
  updateTaskProgress,
  completeTask,
  getLatestTasks
}; 